#!/bin/bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/fs_utils.sh"

function usage() {
    echo "Usage:$( basename $0 ) -l <file_list> [-d <root_dir> -o <output_file>] [<file1>...]"
    echo "      文件合并，输出文件列表指定的文件内容到一个文件中"
    echo "      -l <file_list>: 必须,文件列表"
    echo "      -d <root_dir>: 可选，待输出文件所在目录，缺省为当前目录"
    echo "      -o <output_files>: 可选，输出文件，缺省输出到标准输出"
    echo "      <file1> ...: 指定文件列表，可以和-l共同使用"
    exit 1
}

set -e

rootDir="."
outFile="/dev/stdout"

files=()
argCnt=0
while getopts ":l:d:o:" arg
do
    case $arg in
        l)
            # 注意,这里不能使用cat <file> | while read line
            # 因为cat命令会导致新shell的启动, 导致fs变成新shell的变量
            while read line
            do
                if [[ "${line}" =~ (^[ \t]*#.*) ]]
                then
                    # 忽略注释行
                    continue
                else
                    files[${#files[@]}]="$line"
                fi
            done < $OPTARG
            argCnt=$(( $argCnt + 2 ))
            ;;
        d)
            # 搜索目录
            rootDir="$OPTARG"
            argCnt=$(( $argCnt + 2 ))
            ;;
        o)
            # 输出文件
            outFile="$OPTARG"
            argCnt=$(( $argCnt + 2 ))
            ;;
        ?)
            # 错误选项
            echo "Unknown options: ${OPTARG}"
            usage
    esac
done

shift ${argCnt}
# echo $argCnt
# echo $rootDir
# echo $outFile
# echo "${files[@]}"
# exit

while [ $# -gt 0 ]
do
    files[${#files[@]}]="$1"
    shift
done

if [ 0 -eq ${#files[@]} ]
then 
    usage
fi

# 清空输出文件
echo > ${outFile}

for f in "${files[@]}"
do
    p="${rootDir}/$f"
    if [ -f "$p" ]
    then
        echo "# ============================================================" >> "${outFile}"
        echo "# file: $f " >> "${outFile}"
        echo "# ============================================================" >> "${outFile}"
        cat "$p" >> "${outFile}"
    else
        echo "$p not found" > /dev/stderr
    fi
done
